package com.ocp.common.jasypt.encryptor;

import com.ocp.common.jasypt.constant.EncryptorConstant;
import com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties;
import org.jasypt.encryption.StringEncryptor;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 自定义字符串加密器
 * @author kongyin
 * @date 2022/02/18 19:20
 */
@Configuration
@EnableConfigurationProperties(JasyptEncryptorConfigurationProperties.class)
public class CustomStringEncryptor {

    @Autowired
    private JasyptEncryptorConfigurationProperties properties;

    @Bean(EncryptorConstant.BEAN_NAME)
    public StringEncryptor stringEncryptor() {
        PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPassword(EncryptorConstant.PASSWORD);
        config.setAlgorithm(properties.getAlgorithm());
        config.setKeyObtentionIterations(properties.getKeyObtentionIterations());
        config.setPoolSize(properties.getPoolSize());
        config.setProviderName(properties.getProviderName());
        config.setSaltGeneratorClassName(properties.getSaltGeneratorClassname());
        config.setStringOutputType(properties.getStringOutputType());
        encryptor.setConfig(config);
        return encryptor;
    }
}
